<template>
  <div>
    {{ counter }}
    <button @click="addCounter">+</button>
    <br />
    {{ person.name + person.age }}
    <button @click="updatePerson">修改对象</button>
    <button @click="changeAge">修改年龄</button>
  </div>
  <br />
  {{ obj.a.b.c }}
  <button @click="obj.a.b.c++">++</button>
  <br />
  {{ p4.name }}{{ p4.car }}
  <button @click="changeCar">修改p4</button>
  <button @click="changeP4">修改p4对象</button>
</template>
<script lang="ts">
export default {
  name: "myWatch",
};
</script>
<script setup lang="ts">
import { reactive, ref, watch } from "vue";

function addCounter() {
  counter.value++;
}
let counter = ref(0);
//监视基本类型
const stopWatch = watch(counter, (newVal, oldVal) => {
  console.log(`newVal:${newVal},oldVal:${oldVal}`);
  if (newVal > 10) {
    stopWatch();
  }
});
let person = ref({ name: "张三", age: 20 });
//监视对象类型
const objWatch = watch(
  person,
  (newVal, oldVal) => {
    console.log(newVal, oldVal);
  },
  { deep: true }
);
function updatePerson() {
  person.value = { name: "李四", age: 25 };
}
function changeAge() {
  person.value.age += 1;
}
//监视对象类型 reactive 默认深度监视
let obj = reactive({ a: { b: { c: 1 } } });
watch(obj, (newVal, oldVal) => {
  console.log(newVal, oldVal);
});
//监视对象里的属性，如果是基本属性，需要改成带返回值的getter
let watck4 = watch(
  () => person.value.name,
  (newVal, oldVal) => {
    console.log(newVal, oldVal);
  }
);
let p4 = reactive({ name: "李四", car: "海狮" });
//监视对象里的属性，如果是对象，需要改成带返回值的getter
watch(p4, (newVal, oldVal) => {
  console.log(newVal, oldVal);
});
function changeCar() {
  p4.car = "宝马";
}
function changeP4() {
  Object.assign(p4, { name: "666", car: "奔驰" });
}
</script>

<style></style>
